package com.jinke.uang.main;

import android.annotation.SuppressLint;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.jinke.uang.AppApplication;
import com.jinke.uang.R;
import com.jinke.uang.adapter.ProductAdapter;
import com.jinke.uang.base.BaseFragment;
import com.jinke.uang.base.BaseResponse;
import com.jinke.uang.constant.HttpConstant;
import com.jinke.uang.model.MainModule;
import com.jinke.uang.presenter.CommonPresenter;
import com.jinke.uang.bean.MoneyProductData;
import com.jinke.uang.common.RouterMap;
import com.jinke.uang.cache.Acache;
import com.jinke.uang.cache.AcacheKeys;
import com.jinke.uang.common.DialogManager;
import com.jinke.uang.common.NoDoubleClickListener;
import com.jinke.uang.common.UserInfo;
import com.jinke.uang.constant.Constant;
import com.jinke.uang.bean.OrderItemData;

import com.jinke.uang.permission.IPermisson;
import com.jinke.uang.permission.Permission;
import com.jinke.uang.rxbus.EventMsg;
import com.jinke.uang.rxbus.Events;
import com.jinke.uang.rxbus.RxBus;
import com.jinke.uang.ui.activity.personal.BorrowActivity;
import com.jinke.uang.utils.ToastUtils;
import com.jinke.uang.view.GrantPermissionDialog;
import com.jinke.uang.view.RepaymentDialog;

import java.util.ArrayList;

import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;

@SuppressLint("CheckResult")
public class MainFragment extends BaseFragment<CommonPresenter,MainModule> implements IPermisson{

    @BindView(R.id.linLogin)
    LinearLayout linLogin;

    @BindView(R.id.linNotice)
    LinearLayout linNotice;
//    @BindView(R.id.banner)
//    MZBannerView bannerView;
    @BindView(R.id.iv_header)
    ImageView ivHeader;

    @BindView(R.id.rv_product)
    RecyclerView rvProduct;
    private ProductAdapter productAdapter;

    private GrantPermissionDialog grantPermissionDialog;
    private Permission permission;
    private OrderItemData orderItemData;

    //产品数据的
    private ArrayList<MoneyProductData> list=new ArrayList<>();


    @Override
    protected void onInitViews(View rootView) {
        ButterKnife.bind(this, rootView);
        //banner初始化
//        mPresenter.getData(HttpConstant.NOTICE_CHANNEL,null);
//        bannerView.setDelayedTime(5000);
//        bannerView.setIndicatorVisible(true);

        productAdapter = new ProductAdapter(getContext(), list);
        rvProduct.setLayoutManager(new GridLayoutManager(getContext(), 2));
        rvProduct.setAdapter(productAdapter);
    }

    @Override
    protected int getContentResId() {
        return R.layout.fragment_main;
    }

    @Override
    protected CommonPresenter getPresenter() {
        return new CommonPresenter();
    }

    @Override
    protected MainModule getModule() {
        return new MainModule();
    }

    @Override
    protected void onUiReady() {

        //产品点击的
        productAdapter.setOnItemClickListener(new ProductAdapter.OnItemClickListener() {
            @Override
            public void onClick(View view, int position) {
                if (UserInfo.isLogin()) {
                    if ("1".equals(productAdapter.getData().get(position).getRangeStatus())) {
                        ARouter.getInstance().build(RouterMap.BORROW_PAGE).withSerializable
                                // todo mvp测试修改  BorrowActivity
                                (BorrowActivity.MONEY_DATA, productAdapter.getData().get(position)).navigation();
                    } else {
                        ToastUtils.showShort(getActivity(), getResources().getString(R.string
                                .loan_level_too_low));
                    }
                } else {
                    ARouter.getInstance().build(RouterMap.LOGIN_METNOD_PAGE).navigation();
                }
            }
        });

        permission = new Permission(getActivity(), this);

        //风险提醒
        checkAppPermission();

        RxBus.getInstance().toObservable().map(new Function<Object, EventMsg>() {
            @Override
            public EventMsg apply(Object o) throws Exception {
                return (EventMsg) o;
            }
        }).subscribe(new Consumer<EventMsg>() {
            @Override
            public void accept(EventMsg eventMsg) throws Exception {
                if (eventMsg != null) {
                    if (Events.LOGIN.equals(eventMsg.getMsg())) {
                        processUI();
                    } else if (Events.LOGOUT.equals(eventMsg.getMsg())) {
                        // 退出登陆
                        linLogin.setVisibility(View.VISIBLE);
                    }
                }
            }
        });

        linNotice.setOnClickListener(new NoDoubleClickListener() {
            @Override
            public void onNoDoubleClick(View v) {
                super.onNoDoubleClick(v);
                RepaymentDialog dialog = new RepaymentDialog(getContext(), R.style.normal_dialog);
                dialog.setContent(orderItemData);
                dialog.setStatus(orderItemData.getStatus());
                DialogManager.getManager().showDialogStack(dialog);
            }
        });

    }

    //获取风险提醒
    private void checkAppPermission() {
        permission = new Permission(getActivity(), this);

        String grant = Acache.get(AppApplication.getContext()).getAsString(AcacheKeys.GRANT);
        if (TextUtils.isEmpty(grant)) {
            grantPermissionDialog = new GrantPermissionDialog(getContext());
            grantPermissionDialog.show();
            grantPermissionDialog.setOnClickListener(new GrantPermissionDialog
                    .GrantPermissionDialogCallBack() {
                @Override
                public void onConfirm() {
                    permission.requestAll();
                }

                @Override
                public void onCancel() {
                    getActivity().finish();
                }
            });
        } else {
            sendUpdateMsg();
        }
    }

    private void sendUpdateMsg() {
        EventMsg eventMsg = new EventMsg();
        eventMsg.setMsg(Events.UPDATE);
        RxBus.getInstance().post(eventMsg);
        mPresenter.getData(HttpConstant.GET_PRODUCT,null);
        //todo 登录
        if (UserInfo.isLogin()) {
            mPresenter.getData(HttpConstant.VERIFY_DATA_STATUS,null);
            //当前账单弹窗
            mPresenter.getData(HttpConstant.ORDER_DATA,null,"110");
        }
    }

    /**
     * 加载数据
     */
    private void processUI() {
        //暂时先不获取轮播图
        showLoadingView();
        //获取产品数据
        mPresenter.getData(HttpConstant.GET_PRODUCT,null);
    }

    /**
     * 重新进入App没有数据，调用获取产品数据接口
     */
    @Override
    public void onResume() {
        super.onResume();
        mPresenter.getData(HttpConstant.GET_PRODUCT,null);
    }


    @Override
    public void onSuccess(int result) {
        if (result == 1) {
            Acache.get(AppApplication.getContext()).put(AcacheKeys.GRANT, "1");
            grantPermissionDialog.hide();
            sendUpdateMsg();
        }
    }

    /**
     * 权限获取成功
     *
     * @param object
     */
    @Override
    public void onSuccess(Object object) {
        Acache.get(AppApplication.getContext()).put(AcacheKeys.GRANT, true);
        grantPermissionDialog.hide();
        //判断
        EventMsg msg = new EventMsg();
        msg.setMsg(Events.UPDATE);
        RxBus.getInstance().post(msg);
        processUI();
    }

    @Override
    public void showResponse(int apiType, String listType, Object o) {
        dismissLoadingView();
        if(apiType== HttpConstant.VERIFY_DATA_STATUS){

        }

        else if(apiType==HttpConstant.GET_PRODUCT){  //产品等级
            BaseResponse<ArrayList<MoneyProductData>> response =
                    (BaseResponse<ArrayList<MoneyProductData>>) o;
            if (response.getStatus() == Constant.HTTP_OK) {
                 productAdapter.setData(response.getData());
                 productAdapter.setSelectItem(0);
                 productAdapter.notifyDataSetChanged();
            } else {
                ToastUtils.showShort(getActivity(), response.getMessage());
            }
        }

        else if(apiType==HttpConstant.ORDER_DATA){ //订单类型
            BaseResponse<ArrayList<OrderItemData>> borrowingResponse = (BaseResponse<ArrayList<OrderItemData>>) o;
            if (borrowingResponse.getStatus() == Constant.HTTP_OK) {
                if (borrowingResponse!=null && borrowingResponse.getData().size()>0) {
                    linNotice.setVisibility(View.VISIBLE);
                    orderItemData = borrowingResponse.getData().get(0);
                    RepaymentDialog dialog = new RepaymentDialog(getContext(), R.style.normal_dialog);
                    dialog.setContent(orderItemData);
                    dialog.setStatus(orderItemData.getStatus());
                    DialogManager.getManager().showDialogStack(dialog);
                } else {
                    linNotice.setVisibility(View.GONE);
                }
            } else {
                linNotice.setVisibility(View.GONE);
                ToastUtils.showShort(getActivity(), borrowingResponse.getMessage());
            }
        }

        else if(apiType==HttpConstant.NOTICE_CHANNEL){  //公告轮播
//            if (response.getStatus() == Constant.HTTP_OK) {
//            if (response.hasData()) {
//                ivHeader.setVisibility(View.GONE);
//                bannerView.setVisibility(View.VISIBLE);
//                bannerView.setPages(response.getData(), new MZHolderCreator<BannerViewHolder>() {
//                    @Override
//                    public BannerViewHolder createViewHolder() {
//                        return new BannerViewHolder();
//                    }
//                });
//                if (response.getData().size() > 1) {
//                    bannerView.start();
//                } else {
//                    bannerView.setCanLoop(false);
//                }
//            } else {
//                bannerView.setVisibility(View.GONE);
//                ivHeader.setVisibility(View.VISIBLE);
//            }
//        } else {
//            ToastUtils.showShort(getActivity(), response.getMessage());
//        }
        }
    }

    @Override
    public void showError(Throwable e) {
        dismissLoadingView();
    }
}
